<template>
    <div class="category-container">
        <!-- 顶部操作栏 -->
        <div class="top-bar">
            <div class="search-area">
                <el-input v-model="searchForm.keyword" placeholder="输入类别名称查询"
                    style="width: 200px; margin-right: 10px;" />
                <el-select v-model="searchForm.status" placeholder="显示启用类别" style="width: 150px; margin-right: 10px;">
                    <el-option label="全部" value="-1"></el-option>
                    <el-option label="启用" value="1"></el-option>
                    <el-option label="禁用" value="0"></el-option>
                </el-select>
                <el-button type="primary" @click="searchSupplierType">查询</el-button>
            </div>

            <div class="action-buttons">
                <el-button class="!ml-0" type="primary" @click="openAddDialog">
                    新增
                </el-button>
                <el-button @click="batchClose">禁用</el-button>
                <el-button @click="batchOpen">启用</el-button>
                <el-button @click="refresh">刷新</el-button>
            </div>


            <el-dialog v-model="dialogFormVisible" :title="dialogSupplierType === 'add' ? '新增供应商类别' : '编辑供应商类别'"
                width="500">
                <el-form :model="form">
                    <el-form-item label="上级分类" :label-width="formLabelWidth">
                        <el-tree-select v-model="form.parentId" :data="treeSelectData" filterable style="width: 240px"
                            :props="{ value: 'id', label: 'name', children: 'children' }" :check-strictly="true">

                            <template #default="{ data }">
                                <span>
                                    <el-icon>
                                        <Folder v-if="data.children && data.children.length > 0" />
                                        <Document v-else />
                                    </el-icon>
                                    {{ data.name }}
                                </span>
                            </template>
                        </el-tree-select>
                    </el-form-item>

                    <el-form-item label="类别名称" :label-width="formLabelWidth">
                        <el-input v-model="form.name" autocomplete="off" style="width: 240px" />
                    </el-form-item>


                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button type="primary" @click="saveSupplierType" :loading="saving">
                            确认
                        </el-button>
                        <el-button @click="dialogFormVisible = false">取消</el-button>
                    </div>
                </template>
            </el-dialog>
        </div>

        <!-- 数据表格 -->
        <el-table :data="searchMode ? supplierTypeList : treeData" border style="width: 100%" row-key="id"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" :default-expand-all="!searchMode"
            v-loading="tableLoad" @selection-change="handleSelectionChange">

            <el-table-column type="selection" width="55" />

            <el-table-column prop="name" label="类别" width="300">
                <template #default="{ row }">
                    {{ row.name }}
                </template>
            </el-table-column>

            <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                    <el-switch :model-value="row.status" :active-value="1" :inactive-value="0"
                        @change="() => handleStatusChange(row)" />
                </template>
            </el-table-column>

            <el-table-column prop="operation" label="操作" width="100">
                <template #default="{ row }">
                    <el-button size="small" @click="openEditDialog(row.id)">
                        <el-icon>
                            <Edit />
                        </el-icon>
                    </el-button>
                    <el-button size="small" @click="deleteSupplierType(row)">
                        <el-icon>
                            <Delete />
                        </el-icon>
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="demo-pagination-block" style="float: right;">
            <span style="font-size: 14px;">共 {{ supplierTypeList.length }} 条</span>
        </div>
    </div>

</template>

<script setup>
import { computed, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const formLabelWidth = '80px'

// 是否在搜索
const searchMode = ref(false)

// 表格加载状态
const tableLoad = ref(false)

// 保存按钮状态
const saving = ref(false)

// 删除按钮状态
const deleteLoad = ref(false)

// 搜索表单
const searchForm = ref({
    name: '',
    status: '1'
})

// 添加、修改表单
const form = ref({
    id: '',
    parentId: '',
    name: '',
})

// 对话框、对话框类型
const dialogFormVisible = ref(false)
const dialogSupplierType = ref('add')

const openAddDialog = () => {
    dialogFormVisible.value = true
    form.value = {
        parentId: '0',
        name: ''
    }
}

const openEditDialog = async (id) => {
    dialogSupplierType.value = 'edit'
    try {
        const res = await axios.get('/api/basic/supplier/supplierTypeById', { params: { id } })
        if (res.data.code === 5200) {
            form.value = res.data.supplierType
            dialogFormVisible.value = true
        } else {
            ElMessage.error('获取数据失败')
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}


// 供应商类型
const supplierTypeList = ref([])

// 获取供应商类型
const getSupplierList = async () => {
    tableLoad.value = true

    const params = {
        name: searchForm.value.name,
        status: searchForm.value.status == '-1' ? null : searchForm.value.status
    }

    try {
        const res = await axios.get('/api/basic/supplier/allSupplierType', { params })

        if (res.data.code === 5200) {
            supplierTypeList.value = res.data.supplierTypeList
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    } finally {
        tableLoad.value = false
    }
}

// 构建树形数据
const treeData = computed(() => {

    const roots = [] // 根：没有父级分类

    const map = {} // key:id value: 对象 {id:, name:, status:, parentId:, children:[]}

    supplierTypeList.value.forEach(item => {
        map[item.id] = { ...item, children: [] }
    })

    supplierTypeList.value.forEach(item => {
        if (item.parentId === null || item.parentId === '0') {
            roots.push(map[item.id])
        } else {
            const parentObj = map[item.parentId]
            if (parentObj) {
                parentObj.children.push(map[item.id])
            }
        }
    })
    return roots
})

// 树选择器
const treeSelectData = computed(() => {
    const enabledTreeData = treeData.value
    return [
        {
            id: '0',
            name: '全部',
            children: enabledTreeData
        }
    ]
})

// 查询
const searchSupplierType = () => {
    if (searchForm.value.name.trim() != '' || searchForm.value.status == '0') {
        searchMode.value = true
    } else {
        searchMode.value = false
    }
    getSupplierList()
}

// 刷新
const refresh = () => {
    searchForm.value = { name: '', status: '1' }
    searchMode.value = false
    getSupplierList()
}

// 保存类别
const saveSupplierType = async () => {
    saving.value = true
    if (!form.value.parentId) return ElMessage.warning('请选择上级类别')
    if (!form.value.name?.trim()) return ElMessage.warning('请输入类别名称')


    const submitData = {
        ...form.value,
        parentId: form.value.parentId === '0' ? null : form.value.parentId
    }

    try {
        const url = dialogSupplierType.value === 'add' ? '/api/basic/supplier/addSupplierType' : '/api/basic/supplier/updateSupplierType'

        const res = await axios.post(url, submitData)
        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            dialogFormVisible.value = false
            await getSupplierList()
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    } finally {
        saving.value = false
    }
}

// 删除
const deleteSupplierType = async (row) => {

    if (row.children && row.children.length > 0) {
        ElMessage.error('当前类别下有子类别，请先删除子类别')
        return
    }

    try {
        await ElMessageBox.confirm('此操作将永久删除该类别, 是否继续?', '删除类别', { type: 'warning' })
    } catch {
        return ElMessage.info('取消删除')
    }

    deleteLoad.value = true
    try {
        const res = await axios.post('/api/basic/supplier/deleteSupplierType', null, { params: { id: row.id } })
        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            await getSupplierList()
        }
    } catch (error) {
        ElMessage.error(error.message)
    } finally {
        deleteLoad.value = false
    }
}

// 状态变更
const handleStatusChange = async (row) => {
    tableLoad.value = true
    const originalStatus = row.status
    try {
        const res = await axios.post('/api/basic/supplier/updateSupplierTypeStatus', null, {
            params: {
                id: row.id,
                status: originalStatus === 1 ? 0 : 1
            }
        })
        if (res.data.code !== 5200) {
            ElMessage.error('状态更新失败')
        } else {
            ElMessage.success('状态更新成功')
            await getSupplierList()
        }
    } catch (error) {
        ElMessage.error('网络错误，请重试')
    } finally {
        tableLoad.value = false
    }
}

// 选中的对象
const selections = ref([])

// 选中的id
const selectionIds = computed(() => selections.value.map(item => item.id))

// 选中多选框
const handleSelectionChange = (selection) => {
    selections.value = selection
}

// 批量禁用
const batchClose = async () => {
    if (selectionIds.value.length === 0) {
        ElMessage.warning('请先选择')
        return
    }
    await batchUpdateStatus(0)
}

// 批量启用
const batchOpen = async () => {
    if (selectionIds.value.length === 0) {
        ElMessage.warning('请先选择')
        return
    }
    await batchUpdateStatus(1)
}

// 批量修改状态
const batchUpdateStatus = async (status) => {

    const params = {
        ids: selectionIds.value,
        status
    }

    try {
        const res = await axios.post("/api/basic/supplier/batchUpdateSupplierTypeStatus", params)
        if (res.data.code === 5200) {
            ElMessage.success("修改成功")
            await getSupplierList()
        } else {
            ElMessage.error("修改失败")
        }
    } catch (error) {
        ElMessage.error("修改失败")
    }
}

onMounted(() => {
    getSupplierList()
})

</script>

<style scoped>
.category-container {
    padding: 20px;
    background-color: #fff;
}

.top-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.search-area {
    display: flex;
    align-items: center;
    gap: 10px;
}

.action-buttons {
    display: flex;
    gap: 10px;
}

.el-table {
    margin-top: 10px;
}

/* 表格行样式 */
.el-table .el-table__row:nth-child(even) {
    background-color: #f5f7fa;
}

/* 缩进样式 */
.el-table .el-table__row>td:nth-child(2) {
    padding-left: 20px;
}

/* 操作按钮样式 */
.el-button--small {
    padding: 5px 8px;
    font-size: 12px;
}

/* 开关样式 */
.el-switch {
    margin-left: 10px;
}
</style>